#!/bin/bash
# Copyright (C) 2024-2025 KoudaiPC Computer Technologies Co., Ltd.
# script name: yandi-customize-openwrt.sh
# author: david921518@qq.com

################
# global vars
GLB_WORK_DIR=
GLB_DONE_FILE=
GLB_FIRSTBOOT_ROOT=
GLB_ROOT_DEV=
GLB_ROOT_PART=
GLB_ADMIN_SSH_PORT=
GLB_ADMIN_PASSWORD=
GLB_ADMIN_USERNAME=
GLB_LC_LANGUAGE=
GLB_LC_CHARSET=
GLB_SWAP_FILESIZE=
################

user=$(whoami)

# 定义日志格式-前缀
log_prefix="[customize]"
# 定义日志目录和文件名
log_file_dir="/var/log/kpc"
log_file_path="$log_file_dir/firstboot.log"

log_kmsg_path="/dev/kmsg"
log_con_path="/dev/tty1"

function log_init()
{
  # 文件不存在则创建
  if [ ! -d "$log_file_dir" ]; then
    mkdir -p $log_file_dir
    chmod -R 755 $log_file_dir
  fi
  if [ ! -f "$log_file_path" ]; then
    touch $log_file_path
  fi
}

# 定义日志打印格式
function log()
{
  # 定义日志时间格式
  local curtime=$(date "+%Y-%m-%d %H:%M:%S")
  echo "$curtime $log_prefix $@"
  if [ "$user" == "root" ]; then
    echo "$curtime $log_prefix $@" >>$log_file_path
    #sleep 0.1
    echo "$log_prefix [kmsg] $@" >$log_kmsg_path
    sleep 0.1
    #echo "$curtime $log_prefix [con] $@" >$log_con_path
    #sleep 0.1
  fi
}

function log_from_file()
{
  tmpfile=$@
  if [ ! -f "$tmpfile" ]; then
    log "no file [$tmpfile] to log"
    return 1
  fi

  local n=0
  local -a lists
  while read line;
  do
    lists[$n]="$line"
    ((n++))
  done <$tmpfile

  # 定义日志时间格式
  local curtime=$(date "+%Y-%m-%d %H:%M:%S")

  #echo "$curtime $log_prefix $@"
  local i=0
  for i in $( seq 0 $((${#lists[*]} - 1)) )
  do
    echo "$curtime $log_prefix ${lists[i]}"
  done

  if [ "$user" == "root" ]; then
    #echo "$curtime $log_prefix $@" >>$log_file_path
    for i in $( seq 0 $((${#lists[*]} - 1)) )
    do
      echo "$curtime $log_prefix ${lists[i]}" >>$log_file_path
    done

    #sleep 0.1

    #echo "$log_prefix [kmsg] $@" >$log_kmsg_path
    for i in $( seq 0 $((${#lists[*]} - 1)) )
    do
      echo "$curtime $log_prefix ${lists[i]}" >$log_kmsg_path
      [ $((i%10)) -eq 9 ] || sleep 0.1
    done

    #sleep 0.1

    #echo "$curtime $log_prefix [con] $@" >$log_con_path
    #for i in $( seq 0 $((${#lists[*]} - 1)) )
    #do
    #  echo "$curtime $log_prefix ${lists[i]}" >$log_con_path
    #done

    #sleep 0.1
  fi
}

# loop forever to reboot
function force_reboot()
{
  log "force reboot now!"
  while true; do reboot; sleep 9; done
}

# fix all kinds of possible broken issues
function fix_possible_broken()
{
  log "apt-get --fix-broken install -y"
  apt-get --fix-broken install -y

  log "dpkg -C"
  dpkg -C
  log "dpkg --configure -a"
  dpkg --configure -a
}

function get_work_dir()
{
  ################
  # /kpcos/distro/yandi/releases/0.5/ports/amd64/guest/yandi-customize-debian.sh
  # /kpcos/distro/yandi/releases/0.5/ports/amd64/root/etc/zzz-firstboot
  ################

  local real_path=$(realpath $0)
  GLB_WORK_DIR=$(dirname "$real_path")
  log "WORK DIR is [$GLB_WORK_DIR]"

  local done_file="${real_path}_done"
  log "done_file=[$done_file]"
  real_done_file=$(realpath "$done_file")
  log "real_done_file=[$real_done_file]"

  GLB_DONE_FILE="$real_done_file"
  log "GLB_DONE_FILE=[$GLB_DONE_FILE]"

  local firstboot_root="$GLB_WORK_DIR/../root"
  log "firstboot_root=[$firstboot_root]"
  real_firstboot_root=$(realpath "$firstboot_root")
  log "real_firstboot_root=[$real_firstboot_root]"

  if [ ! -d $real_firstboot_root ]; then
    log "No firstboot root dir [$real_firstboot_root]."
    exit 1
  fi

  GLB_FIRSTBOOT_ROOT="$real_firstboot_root"
  log "GLB_FIRSTBOOT_ROOT=[$GLB_FIRSTBOOT_ROOT]"
}

# save installed packages list
function save_pkg_list()
{
  if [ "$1" == "" ]; then
    log "save_pkg_list() filename is empty, do nothing!"
    return
  fi
  local list_file="$PWD"/$1
  log "save bootstrap packages list to $list_file"
  [ -f $list_file ] || dpkg -l >$list_file
}

# get ROOT device from mount info
function get_root_dev()
{
  local line=$(mount | grep " on / type ")
  if [ x"$line" != x ]; then
    root_part=$(echo $line | awk '{print $1}')
    log "root_part=[$root_part]"
    case "$root_part" in
      "/dev/sd"* )
        GLB_ROOT_DEV=${root_part:0:8}
        GLB_ROOT_PART=$root_part
        ;;
      "/dev/vd"* )
        GLB_ROOT_DEV=${root_part:0:8}
        GLB_ROOT_PART=$root_part
        ;;
      * )
        ;;
    esac
    log "GLB_ROOT_DEV=[$GLB_ROOT_DEV] GLB_ROOT_PART=[$GLB_ROOT_PART]"
  fi
}

# start kpc-heartbeat
function start_heartbeat()
{
  heartbeat_conf=/etc/kpc/heartbeat.conf
  heartbeat_file=/usr/sbin/kpc-heartbeat.sh
  heartbeat_lock=/tmp/kpc-hearbeat.lock
  if [ -x $heartbeat_file ]; then
    log "start kpc-heartbeat"
    (flock -n $heartbeat_lock -c "echo 9 >$heartbeat_conf ; ($heartbeat_file)")&
  fi
}

# run bootstrap configurating
function run_bootstrap_config()
{
  local admin_ssh_port=""
  local admin_password=""
  local admin_username=""
  local lc_language=""
  local lc_charset=""
  local swap_filesize=""
  local wifi_backend=""
  local wifi_dev=""
  local wifi_addr=""
  local wifi_mode=""
  local wifi_net=""
  local wifi_pass=""

  local conf_file=/etc/kpc/bootstrap.conf
  if [ -f $conf_file ]; then
    log "start to configurate bootstrap environment"

    local n=0
    local -a lists
    while read line;
    do
      lists[$n]="$line"
      ((n++))
    done <$conf_file

    local i=0
    for i in $( seq 0 $((${#lists[*]} - 1)) )
    do
      #log "lists[$i]=[${lists[i]}]"
      local name=$(echo ${lists[i]} | awk '{print $1}')
      local val=$(echo ${lists[i]} | awk '{print $2}')
      #log "name=[$name] val=[$val]"
      case "$name" in
        "#"* )
          #log "it's comment"
          ;;
        "" )
          #log "it's empty line"
          ;;
        "admin.ssh_port" )
          admin_ssh_port="$val"
	  if [ $admin_ssh_port -gt 65535 ]; then
            log "admin.ssh_port=[$admin_ssh_port] is invalid"
	    continue;
	  fi
	  if [ $admin_ssh_port -lt 22 ]; then
            log "admin.ssh_port=[$admin_ssh_port] is invalid"
	    continue;
	  fi
          log "admin SSH port set to [$admin_ssh_port]"
          GLB_ADMIN_SSH_PORT=$admin_ssh_port
          ;;
        "admin.password" )
          admin_password="$val"
          log "admin pasword set to [$admin_password]"
          GLB_ADMIN_PASSWORD=$admin_password
          ;;
        "admin.username" )
          admin_username="$val"
          log "admin username set to [$admin_username]"
          GLB_ADMIN_USERNAME=$admin_username
          ;;
        "locale.language" )
          lc_language="$val"
          log "LANGUAGE set to [$lc_language]"
          GLB_LC_LANGUAGE=$lc_language
          ;;
        "locale.charset" )
          lc_charset="$val"
          log "CHARSET set to [$lc_charset]"
          GLB_LC_CHARSET=$lc_charset
          ;;
        "swap.filesize" )
          swap_filesize="$val"
          log "SWAP file size set to [$swap_filesize]"
          GLB_SWAP_FILESIZE=$swap_filesize
          ;;
        "wifi.backend" )
          if [ "$val" == "iwd" ]; then
            log "enable iwd network configuration"
            wifi_backend="$val"
            iwd_main_conf=/etc/iwd/main.conf
            sed "s/#EnableNetworkConfiguration=true/EnableNetworkConfiguration=true/g" -i $iwd_main_conf
            #log_from_file $iwd_main_conf
          fi
          ;;
        "wifi.device_name" )
          wifi_dev="$val"
          log "wifi_dev=[$wifi_dev]"
          ;;
        "wifi.device_address" )
          wifi_addr="$val"
          log "wifi_addr=[$wifi_addr]"
          ;;
        "wifi.mode" )
          wifi_mode="$val"
          log "wifi_mode=[$wifi_mode]"
          ;;
        "wifi.network" )
          wifi_net="$val"
          log "wifi_net=[$wifi_net]"
          ;;
        "wifi.passphrase" )
          wifi_pass="$val"
          log "wifi_pass=[$wifi_pass]"
          ;;
        * )
          log "unknown option=[$name]"
          ;;
      esac
    done

    if [ "$wifi_backend" == "iwd" ]; then
      log "systemctl --now enable iwd"
      systemctl --now enable iwd
      sleep 3
      if [ x"$wifi_dev" == x ]; then
        #iwctl device list
        line=$(iwctl device list | grep "station" )
        log "line=[$line]"
        if [ x"$line" == x ]; then
          log "no station mode wifi device found, exit now"
          exit 1
        fi
        #dummy=$(echo $line | awk '{print $1}')
        dummy=$(echo $line | awk '{print $1}')
        log "dummy=[$dummy]"
        #dev_name=$(echo $line | awk '{print $2}')
        wifi_dev=$(echo $line | awk '{print $2}')
        log "wifi_dev=[$wifi_dev]"
        #dev_addr=$(echo $line | awk '{print $3}')
        wifi_addr=$(echo $line | awk '{print $3}')
        log "wifi_addr=[$wifi_addr]"
        #dev_powered=$(echo $line | awk '{print $4}')
        wifi_powered=$(echo $line | awk '{print $4}')
        log "wifi_powered=[$wifi_powered]"
        #dev_adapter=$(echo $line | awk '{print $5}')
        wifi_adapter=$(echo $line | awk '{print $5}')
        log "wifi_adapter=[$wifi_adapter]"
        #dev_mode=$(echo $line | awk '{print $6}')
        wifi_mode=$(echo $line | awk '{print $6}')
        log "wifi_mode=[$wifi_mode]"

        log "detect wifi_dev=[$wifi_dev]"
        if [ x"$wifi_dev" == x ]; then
          log "no wifi device found, exit now"
          exit 1
        fi
      fi
      if [ x"$wifi_dev" != x ]; then
        line=$(iwctl device list | grep " $wifi_dev " )
        log "line=[$line]"
        if [ x"$line" != x ]; then
          dummy=$(echo $line | awk '{print $1}')
          dev_name=$(echo $line | awk '{print $2}')
          dev_addr=$(echo $line | awk '{print $3}')
          dev_powered=$(echo $line | awk '{print $4}')
          dev_adapter=$(echo $line | awk '{print $5}')
          dev_mode=$(echo $line | awk '{print $6}')
          log "dev_mode=[$dev_mode]"
          if [ "$dev_mode" == "station" ]; then
            #iwctl station wlan0 scan
            tmpfile=$(mktemp)
            iwctl station $wifi_dev scan 2>&1 | tee $tmpfile
            log_from_file $tmpfile
            rm -f $tmpfile
            sleep 3

            #iwctl station wlan0 get-networks
            tmpfile=$(mktemp)
            iwctl station $wifi_dev get-networks 2>&1 | tee $tmpfile
            log_from_file $tmpfile
            rm -f $tmpfile

            #iwctl --passphrase "mysecret" station wlan0 connect "SSID"
            log "iwctl --passphrase $wifi_pass station $wifi_dev connect $wifi_net"
            iwctl --passphrase "$wifi_pass" station $wifi_dev connect "$wifi_net"
            sleep 3

            #iwctl station wlan0 show
            tmpfile=$(mktemp)
            iwctl station $wifi_dev show 2>&1 | tee $tmpfile
            log_from_file $tmpfile
            rm -f $tmpfile
            log "/etc/init.d/iwd restart"
            /etc/init.d/iwd restart
            sleep 1
          fi
        fi
      fi
      #iwctl station wlan0 scan
      #iwctl station wlan0 get-networks
      #iwctl --passphrase "mysecret" station wlan0 connect "SSID"
      #iwctl station wlan0 show
      #/etc/init.d/iwd restart
      #iwctl station wlan0 disconnect
    fi #endof wifi_backend==iwd
  fi
}

# check WAN interface
function check_wan_iface()
{
  local COUNTER=0
  local dev_array=($(ip route | awk '/default/ {print $5}'))
  local iface_dev=${dev_array[0]}
  while [ "$iface_dev"x == x ]; do
    sleep 1
    ((COUNTER++))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get default route device interface, exit now"
      exit 1
    fi
    dev_array=($(ip route | awk '/default/ {print $5}'))
    iface_dev=${dev_array[0]}
  done

  COUNTER=0
  local WAN_IP=$(ip addr show $iface_dev | grep "inet" | head -n 1 | awk '/inet/ {print $2}' | cut -d'/' -f1)
  while [ "${WAN_IP}"x == x ]; do
    sleep 1
    ((COUNTER++))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get WAN IP address, reboot now"
      force_reboot
    fi
    log "get WAN IP address again"
    WAN_IP=$(ip addr show $iface_dev | grep "inet" | head -n 1 | awk '/inet/ {print $2}' | cut -d'/' -f1)
  done
  log "WAN IP=[${WAN_IP}]"
}

function apt_install_pkg()
{
  PKG_NAME="$1"
  log "apt-get install $PKG_NAME"

  if [ "${PKG_NAME}"x == x ]; then
    log "Error: PKG_NAME is empty!!!"
    force_reboot
  fi

  export DEBIAN_FRONTEND=noninteractive
  export DEBIAN_PRIORITY=critical
  tmpfile=$(mktemp)
  apt-get install -y --option Dpkg::Options::=--force-confold --option Dpkg::Options::=--force-confdef "$PKG_NAME" 2>&1 | tee $tmpfile
  #log_from_file $tmpfile
  rm -f $tmpfile
  sleep 0.1

  let COUNTER=0
  PKG_INSTALLED=$(apt list --installed | grep "^$PKG_NAME/" | awk '{split($0,a,"/"); print a[1]}')
  while [ "${PKG_INSTALLED}"x != "${PKG_NAME}"x ]; do
    log "Try to install $PKG_NAME again"
    sleep 0.1
    let COUNTER=$COUNTER+1
    if [ $COUNTER -gt 29 ]; then
      log "Can't install $PKG_NAME , reboot now"
      while true; do reboot; sleep 9; done
    fi
    tmpfile=$(mktemp)
    apt-get update 2>&1 | tee $tmpfile
    #log_from_file $tmpfile
    rm -f $tmpfile
    sleep 0.1
    tmpfile=$(mktemp)
    apt-get install -y --option Dpkg::Options::=--force-confold --option Dpkg::Options::=--force-confdef "$PKG_NAME" 2>&1 | tee $tmpfile
    #log_from_file $tmpfile
    rm -f $tmpfile
    sleep 0.1
    PKG_INSTALLED=$(apt list --installed | grep "^$PKG_NAME/" | awk '{split($0,a,"/"); print a[1]}')
  done
}

function apt_remove_pkg()
{
  PKG_NAME="$1"
  log "apt-get remove $PKG_NAME"

  if [ "${PKG_NAME}"x == x ]; then
    log "Error: PKG_NAME is empty!!!"
    force_reboot
  fi

  tmpfile=$(mktemp)
  apt-get remove -y "$PKG_NAME" 2>&1 | tee $tmpfile
  #log_from_file $tmpfile
  rm -f $tmpfile

  let COUNTER=0
  PKG_REMOVED=$(apt list --installed | grep "^$PKG_NAME/" | awk '{split($0,a,"/"); print a[1]}')
  while [ "$PKG_REMOVED" == "$PKG_NAME" ]; do
    log "Try to remove $PKG_NAME again"
    sleep 0.1
    let COUNTER=$COUNTER+1
    if [ $COUNTER -gt 29 ]; then
      log "Can't remove $PKG_NAME , reboot now"
      force_reboot
    fi
    tmpfile=$(mktemp)
    apt-get remove -y "$PKG_NAME" 2>&1 | tee $tmpfile
    #log_from_file $tmpfile
    rm -f $tmpfile
    PKG_REMOVED=$(apt list --installed | grep "^$PKG_NAME" | awk '{split($0,a,"/"); print a[1]}')
  done
}

# 0. init script
log_init
log "[customize-debian] START"
fix_possible_broken
get_work_dir
if [ -f $GLB_DONE_FILE ]; then
  log "exist file $GLB_DONE_FILE , exit now"
  exit 1
fi
get_root_dev
start_heartbeat
run_bootstrap_config
check_wan_iface
save_pkg_list pre_customize_debian_pkgs.txt

log "PATH=[$PATH]"

# 0. enable swap
log "enable swap"
fstab_file=/etc/fstab
sys_swapfile=/swapfile
if [ x"$GLB_SWAP_FILESIZE" != x ]; then
  swapfile_size="$GLB_SWAP_FILESIZE"
else
  swapfile_size=1G
fi

swapon_file=$(swapon | grep "$sys_swapfile" | awk '{print $1}')
if [ "$swapon_file" != "$sys_swapfile" ]; then
  fallocate -l $swapfile_size $sys_swapfile
  chmod 0600 $sys_swapfile
  mkswap $sys_swapfile
  swapon $sys_swapfile
fi

read_line=$(grep "$sys_swapfile swap swap defaults 0 0" $fstab_file)
log "read_line=[$read_line]"
if [ x"$read_line" == x ]; then
  log "add [$sys_swapfile swap swap defaults 0 0] to $fstab_file"
  echo "$sys_swapfile swap swap defaults 0 0" >>$fstab_file
fi

# 1. change password
if [ x"$GLB_ADMIN_PASSWORD" != x ]; then
  def_passwd="$GLB_ADMIN_PASSWORD"
else
  def_passwd="KoudaiPC@123"
fi
log "default root password is [$def_passwd]"
tmpfile=$(mktemp)
echo "$def_passwd" >$tmpfile
echo "$def_passwd" >>$tmpfile
passwd root <$tmpfile
rm -f $tmpfile

log "fix potential dpkg issues"
dpkg -C
dpkg --configure -a

# 2. install dropbear
log "install dropbear"
apt-get update
#apt-get install -y dropbear
apt_install_pkg dropbear

if [ x"$GLB_ADMIN_SSH_PORT" == x ]; then
  # use default port 50022
  log "change dropbear port to 50022"
  #sed "s/#DROPBEAR_PORT=22/DROPBEAR_PORT=50022/g" -i /etc/default/dropbear
  sed "s/DROPBEAR_PORT=22/DROPBEAR_PORT=50022/g" -i /etc/default/dropbear
  sed "s/DROPBEAR_PORT=22/DROPBEAR_PORT=50022/g" -i /etc/init.d/dropbear
else
  # use setting port $GLB_ADMIN_SSH_PORT
  log "change dropbear port to $GLB_ADMIN_SSH_PORT"
  #sed "s/#DROPBEAR_PORT=22/DROPBEAR_PORT=$GLB_ADMIN_SSH_PORT/g" -i /etc/default/dropbear
  sed "s/DROPBEAR_PORT=22/DROPBEAR_PORT=$GLB_ADMIN_SSH_PORT/g" -i /etc/default/dropbear
  sed "s/DROPBEAR_PORT=22/DROPBEAR_PORT=$GLB_ADMIN_SSH_PORT/g" -i /etc/init.d/dropbear
fi
systemctl daemon-reload
service dropbear restart

# 3. install procps
log "install procps"
#apt-get install -y procps
apt_install_pkg procps

# 4. add banner in profile
log "add banner in profile"
banner_file=/etc/banner
sys_profile=/etc/profile

read_line=$(grep "[ -f $banner_file ] && cat $banner_file" $sys_profile)
log "read_line=[$read_line]"
if [ x"$read_line" == x ]; then
  log "add '[ -f $banner_file ] && cat $banner_file' to $sys_profile"
  sed "9 a\[ -f $banner_file ] && cat $banner_file" -i $sys_profile
fi

# 5. install xfce-desktop
log "install xfce-desktop"
#apt-get install -y task-xfce-desktop
apt_install_pkg task-xfce-desktop
sleep 0.1

# 6. install Chinese Simple Desktop
case "$GLB_LC_LANGUAGE" in
  "zh_TW" )
    log "install Chinese Traditional Desktop Environment"
    #apt-get install -y task-chinese-t-desktop
    apt_install_pkg task-chinese-t-desktop
    ;;
  * )
    log "install Chinese Simple Desktop Environment"
    #apt-get install -y task-chinese-s-desktop
    apt_install_pkg task-chinese-s-desktop
    ;;
esac
sleep 0.1

# 7. setup zh_CN.UTF-8
apt_install_pkg locales-all
log "original default locale"
log "localectl"
tmpfile=$(mktemp)
localectl 2>&1 | tee $tmpfile
log_from_file $tmpfile
rm -f $tmpfile
log "locale"
tmpfile=$(mktemp)
locale 2>&1 | tee $tmpfile
log_from_file $tmpfile
rm -f $tmpfile

conf_file=/etc/locale.conf
case "$GLB_LC_LANGUAGE" in
  "zh_TW" )
    log "set locale to zh_TW.UTF-8"
    #dpkg-reconfigure locales
    log "set to Traditional Chinese"
    lang_name="zh_TW"
    ;;
  * )
    log "set locale to zh_CN.UTF-8"
    #dpkg-reconfigure locales
    log "set to Simple Chinese"
    lang_name="zh_CN"
    ;;
esac

if [ x"$GLB_LC_CHARSET" != x ]; then
  lc_name="${lang_name}.${GLB_LC_CHARSET}"
else
  lc_name="${lang_name}.UTF-8"
fi

#localectl set-locale LANG=zh_CN.UTF-8
localectl set-locale LANG=$lc_name
#localectl set-locale LANGUAGE=zh_CN
localectl set-locale LANGUAGE=$lang_name
echo "LANG=$lc_name" >$conf_file
echo "LANGUAGE=$lang_name" >>$conf_file

log "new default locale"
log "localectl"
tmpfile=$(mktemp)
localectl 2>&1 | tee $tmpfile
log_from_file $tmpfile
rm -f $tmpfile
log "locale"
tmpfile=$(mktemp)
locale 2>&1 | tee $tmpfile
log_from_file $tmpfile
rm -f $tmpfile

log "set /etc/locale.gen"
conf_file=/etc/locale.gen
#sed "s/# zh_TW.UTF-8 UTF-8/zh_TW.UTF-8 UTF-8/g" -i $conf_file
#lc_name="zh_TW.UTF-8"
sed "s/# $lc_name UTF-8/$lc_name UTF-8/g" -i $conf_file

# following language charset be supported all the time
#sed "s/# zh_CN.UTF-8 UTF-8/zh_CN.UTF-8 UTF-8/g" -i $conf_file
fix_lc_name="zh_CN.UTF-8"
sed "s/# $fix_lc_name UTF-8/$fix_lc_name UTF-8/g" -i $conf_file
#sed "s/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/g" -i $conf_file
fix_lc_name="en_US.UTF-8"
sed "s/# $fix_lc_name UTF-8/$fix_lc_name UTF-8/g" -i $conf_file

# 8. set timezone
log "set timezone to Asia/Shanghui"
tz_name="Asia/Shanghai"
timedatectl set-timezone $tz_name

# 9. remove netplan.io
log "remove netplan.io"
#apt-get purge -y netplan.io
apt_remove_pkg netplan.io

# 10. enable NetworkManager control
log "enable NetworkManager control"
conf_file=/etc/NetworkManager/NetworkManager.conf
sed "s/managed=false/managed=true/g" -i $conf_file
systemctl restart NetworkManager

# 11. enable swap

# 12. setup hostname
log "set hostname to YanDi"
hostname_file=/etc/hostname
echo "YanDi" >$hostname_file
hostname -F $hostname_file

# 13. remove libreoffice
log "remove libreoffice"
#apt-get purge -y libreoffice-base-core libreoffice-core libreoffice-common libreoffice-style-colibre
#apt-get autoremove -y
apt_remove_pkg libreoffice-base-core
apt_remove_pkg libreoffice-core
apt_remove_pkg libreoffice-common
apt_remove_pkg libreoffice-style-colibre

# 14. remove goldendict
log "remove goldendict"
#apt-get purge -y goldendict
#apt-get autoremove -y
apt_remove_pkg goldendict
 
# 15. remove xsane
log "remove xsane"
#apt-get purge -y xsane-common xsane
#apt-get autoremove -y
apt_remove_pkg xsane
apt_remove_pkg xsane-common

# 16. remove atril
log "remove atril"
#apt-get purge -y atril-common atril
#apt-get autoremove -y
apt_remove_pkg atril
apt_remove_pkg atril-common

# 17. remove exfalso
log "remove exfalso"
#apt-get purge -y exfalso
#apt-get autoremove -y
apt_remove_pkg exfalso

# 18. install sftp server
log "install sftp server"
#apt-get install -y openssh-sftp-server
apt_install_pkg openssh-sftp-server

log "install ssl-cert"
#apt-get install -y ssl-cert
apt_install_pkg ssl-cert

# 19. install flatpak
log "install flatpak"
#apt-get install -y flatpak
apt_install_pkg flatpak

# 20. install lightdm-autologin-greeter
log "install lightdm-autologin-greeter"
#apt-get install -y lightdm-autologin-greeter
apt_install_pkg lightdm-autologin-greeter

# 21. setup kpc user
if [ x"$GLB_ADMIN_USERNAME" != x ]; then
  def_username="$GLB_ADMIN_USERNAME"
else
  def_username="kpc"
fi
log "set admin username to [$def_username]"

log "default admin user password is [$def_passwd]"
tmpfile=$(mktemp)
echo "$def_passwd" >$tmpfile
echo "$def_passwd" >>$tmpfile
echo '' >>$tmpfile
echo '' >>$tmpfile
echo '' >>$tmpfile
echo '' >>$tmpfile
echo '' >>$tmpfile
echo '' >>$tmpfile
echo '' >>$tmpfile
adduser "$def_username" <$tmpfile
rm -f $tmpfile
usermod -aG adm "$def_username"
usermod -aG audio "$def_username"
#usermod -aG bluetooth "$def_username"
usermod -aG cdrom "$def_username"
usermod -aG dialout "$def_username"
usermod -aG dip "$def_username"
usermod -aG input "$def_username"
usermod -aG netdev "$def_username"
usermod -aG plugdev "$def_username"
usermod -aG pulse-access "$def_username"
usermod -aG render "$def_username"
usermod -aG ssl-cert "$def_username"
usermod -aG staff "$def_username"
usermod -aG sudo "$def_username"
usermod -aG systemd-journal "$def_username"
usermod -aG video "$def_username"

# 22. setup auto login kpc user
log "setup auto login $def_username user"
conf_file=/etc/lightdm/lightdm.conf.d/lightdm-autologin-greeter.conf
sed "s/^autologin-user=AUTOLOGIN-USER-NOT-CONFIGURED/autologin-user=$def_username/g" -i $conf_file

# 23. add locale setup in .bashrc for kpc user
log "add locale setup in .bashrc for kpc user"
kpc_bashrc="/home/$def_username"/.bashrc
kpc_set_user_locale_file=/usr/sbin/kpc-set-user-locale.sh
read_line=$(grep "$kpc_set_user_locale_file" $kpc_bashrc)
log "read_line=[$read_line]"
if [ x"$read_line" == x ]; then
  log "add ($kpc_set_user_locale_file)& to $kpc_bashrc"

  cat <<EOF >>$kpc_bashrc

# always setup user locale
if [ -x $kpc_set_user_locale_file ]; then
  ($kpc_set_user_locale_file)&
fi

EOF
fi

log "user[$def_username] LANG=[$lc_name], LANGUAGE=[$lang_name]"
kpc_user_conf_dir="/home/$def_username"/.config
kpc_user_locale_conf=$kpc_user_conf_dir/locale.conf
mkdir -p $kpc_user_conf_dir
chmod 0700 $kpc_user_conf_dir
chown "${def_username}:${def_username}" $kpc_user_conf_dir -R
echo "LANG=$lc_name" >$kpc_user_locale_conf
echo "LANGUAGE=$lang_name" >>$kpc_user_locale_conf
chown "${def_username}:${def_username}" $kpc_user_locale_conf

# 24. add flatpak setup in .bashrc for kpc user
log "add flatpak setup in .bashrc for kpc user"
kpc_bashrc="/home/$def_username"/.bashrc
kpc_flatpak_file=/usr/sbin/kpc-flatpak-remote-repos.sh
read_line=$(grep "$kpc_flatpak_file" $kpc_bashrc)
log "read_line=[$read_line]"
if [ x"$read_line" == x ]; then
  log "add ($kpc_flatpak_file)& to $kpc_bashrc"

  cat <<EOF >>$kpc_bashrc

# always setup user flatpak remote repos
if [ -x $kpc_flatpak_file ]; then
  ($kpc_flatpak_file)&
fi

EOF
fi

# 25. remove unused pkgs
log "remove unused pkgs"
apt-get autoremove -y

# 26. garantee iproute2 is installed
log "garantee iproute2 is installed"
#apt-get install -y iproute2
apt_install_pkg iproute2

# 27. disable networkd service
log "disable networkd service"
tmpfile=$(mktemp)
systemctl disable systemd-networkd.service 2>&1 | tee $tmpfile
log_from_file $tmpfile
rm -f $tmpfile

tmpfile=$(mktemp)
systemctl disable systemd-networkd.socket 2>&1 | tee $tmpfile
log_from_file $tmpfile
rm -f $tmpfile

#systemctl disable networkd-dispatcher.service 2>&1 | tee $tmpfile

save_pkg_list post_customize_debian_pkgs.txt
touch $GLB_DONE_FILE
sync
#sleep 1

log "[customize-debian] EXIT"
#sleep 1

# restart system
#poweroff
